# \src\crud\sys_dict_value.py
from typing import List, Optional
from sqlalchemy.orm import Session
from src.models import sys_dict_value as models
from src.schemas import sys_dict_value as schemas
from src.schemas import request_model
from src.core import orm_curd
from src.schemas.login_manager import AuthManager


# ---------------------- 单条新增 ----------------------
def create_dict_value(db: Session,
                      auth: AuthManager,
                      value: schemas.SysDictValueCreate) -> dict:
    return orm_curd.Insert(
        db,
        auth,
        models.SysDictValue,
        schemas.SysDictValue,
        "数字字典值",
        [value.dict()],
        ["dict_id", "dict_code"],  # 业务唯一键
        skip_duplicates=True
    )


# ---------------------- 批量新增 ----------------------
def create_dict_values(db: Session,
                       auth: AuthManager,
                       values: List[schemas.SysDictValueCreate]) -> dict:
    return orm_curd.Insert(
        db,
        auth,
        models.SysDictValue,
        schemas.SysDictValue,
        "数字字典值",
        values,
        ["dict_id", "dict_code"],
        skip_duplicates=True
    )


# ---------------------- 分页查询 ----------------------
def get_dict_values(db: Session,
                    auth: AuthManager,
                    page: int = 0,
                    page_size: int = 100,
                    FilterModel: Optional[request_model.QueryModel] = None,
                    id: Optional[str] = None) -> dict:
    return orm_curd.query_with_page(
        db,
        auth,
        models.SysDictValue,
        schemas.SysDictValue,
        id=id,
        filter_model=FilterModel,
        page=page,
        page_size=page_size
    )


# ---------------------- 单条更新 ----------------------
def update_dict_value(db: Session,
                      auth: AuthManager,
                      value_id: str,
                      value: schemas.SysDictValue) -> schemas.SysDictValue:
    update_model = request_model.UpdateModel([
        request_model.UpdateItem(
            pk_names=["id"],
            pk_values=[value_id],
            data=value.dict(exclude_unset=True)
        )
    ])
    return orm_curd.update(
        db,
        auth,
        models.SysDictValue,
        update_model
    )


# ---------------------- 批量更新 ----------------------
def update_dict_values(db: Session,
                       auth: AuthManager,
                       updateModel: request_model.UpdateModel) -> dict:
    return orm_curd.update(
        db,
        auth,
        models.SysDictValue,
        updateModel
    )


# ---------------------- 删除 ----------------------
def delete_dict_values(db: Session,
                       auth: AuthManager,
                       deleteModel: request_model.DeleteModel) -> dict:
    return orm_curd.delete(
        db=db,
        auth=auth,
        model_cls=models.SysDictValue,
        delete_obj=deleteModel
    )
